package cn.iocoder.yudao.module.signature.controller.app.udid;

import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.io.SAXReader;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;

/**
 * @author liujq
 * @date 20241205 23:34
 */
@Tag(name = "管理后台 - 获取udid信息")
@RestController
@RequestMapping("/udid")
@Slf4j
public class UdidController {


    @PostMapping("/getUdid")
    public void getUdid(HttpServletRequest request, HttpServletResponse response) throws Exception {
        response.setContentType("text/html;charset=UTF-8");
        request.setCharacterEncoding("UTF-8");

        //获取HTTP请求的输入流
        InputStream is = request.getInputStream();
        //已HTTP请求输入流建立一个BufferedReader对象
        BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
        StringBuilder sb = new StringBuilder();

        //读取HTTP请求内容
        String buffer = null;
        while ((buffer = br.readLine()) != null) {
            sb.append(buffer);
        }
        String content = sb.toString().substring(sb.toString().indexOf("<?xml"), sb.toString().indexOf("</plist>") + 8);

        System.out.println(content);
        log.info("content:{}", content);


        // 创建xml解析对象
        SAXReader reader = new SAXReader();
        // 定义一个文档
        Document document = null;
        //将字符串转换为
        try {
            document = reader.read(new ByteArrayInputStream(content.getBytes("GBK")));
        } catch (DocumentException e) {
            e.printStackTrace();
        }
        // 获取设备型号  udid  版本号
        String product = document.selectSingleNode("//dict/key[text()='PRODUCT']/following-sibling::string[1]").getText();
        String udid = document.selectSingleNode("//dict/key[text()='UDID']/following-sibling::string[1]").getText();
        String version = document.selectSingleNode("//dict/key[text()='VERSION']/following-sibling::string[1]").getText();
        log.info("product:{},udid:{},version:{}", product, udid, version);

        response.setStatus(301);//301之后i05设备会自动打开safari浏览器

        //获取请求地址里的参数 url
        String url = request.getParameter("url");
        String redirectUrl = "https://"+url+"/mobile/signature_exchange?udid=" + udid + "&product=" + product + "&version=" + version;

        log.info("redirectUrl:{}", redirectUrl);

        response.setHeader("Location",redirectUrl );

    }

    @GetMapping("/getUdIdFile")
    public void getUdIdFile(HttpServletRequest request, HttpServletResponse response){
        response.setContentType("application/x-apple-aspen-config");
        response.setHeader("Content-Disposition", "attachment; filename=\"udid.mobileconfig\"");

        //获取请求域名
        String host = request.getHeader("Host");
        String mobileconfigContent = getMobileconfigContent(host);
        try {
            response.getOutputStream().write(mobileconfigContent.getBytes());
        } catch (Exception e) {
            log.error("getUdIdFile error", e);
        }

    }

    private String getMobileconfigContent(String host){
        return "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
                "<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n" +
                "<plist version=\"1.0\">\n" +
                "    <dict>\n" +
                "        <key>PayloadContent</key>\n" +
                "        <dict>\n" +
                "            <key>URL</key>\n" +
                "            <string>https://"+host+"/app-api/udid/getUdid?url="+host+"</string>\n" +
                "            <key>DeviceAttributes</key>\n" +
                "            <array>\n" +
                "                <string>UDID</string>\n" +
                "                <string>IMEI</string>\n" +
                "                <string>ICCID</string>\n" +
                "                <string>VERSION</string>\n" +
                "                <string>PRODUCT</string>\n" +
                "            </array>\n" +
                "        </dict>\n" +
                "        <key>PayloadOrganization</key>\n" +
                "        <string>获取设备UDID1</string>\n" +
                "        <key>PayloadDisplayName</key>\n" +
                "        <string>官方认证™</string>\n" +
                "        <key>PayloadVersion</key>\n" +
                "        <integer>1</integer>\n" +
                "        <key>PayloadUUID</key>\n" +
                "        <string>3C4DC7D2-E895-3515-419C-0B11D347A651</string>\n" +
                "        <key>PayloadIdentifier</key>\n" +
                "        <string>aptso.profile-service</string>\n" +
                "        <key>PayloadDescription</key>\n" +
                "        <string>获取设备UDID。\n" +
                "（已通过苹果认证，放心安装，点击右上角“安装”开始获取设备UDID码！）\n" +
                "\n" +
                "温馨提示：\n" +
                "如果系统提示输入密码，请输入锁屏密码即可。\n" +
                "\n" +
                "什么是UDID?\n" +
                "UDID，是苹果设备的一个唯一识别码，每台苹果设备都有一个独一无二的编码，这个编码，我们称之为识别码，也叫做UDID(Unique Device Identifier)</string>\n" +
                "        <key>PayloadType</key>\n" +
                "        <string>Profile Service</string>\n" +
                "    </dict>\n" +
                "</plist>";

    }

}